package com.bdqn.easybuy1.servlet;

import com.bdqn.easybuy1.utils.EmptyUtils;
import com.bdqn.easybuy1.utils.PrintUtil;
import com.bdqn.easybuy1.utils.ReturnResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 抽取Servlet的公共父类
 */
public abstract class AbstractServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        Method method = null;   // 获取到要执行的方法
        Object result = null;   // 执行方法的返回结果

        try {
            if (EmptyUtils.isEmpty(action)) {
                result = execute(request, response);
            } else {
                method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
                result = method.invoke(this, request, response);
            }
            toView(request, response, result);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            String viewName = "404.jsp";
            request.getRequestDispatcher(viewName).forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            if (!EmptyUtils.isEmpty(result)) {
                if (result instanceof String) {
                    String viewName = "500.jsp";
                    request.getRequestDispatcher(viewName).forward(request, response);
                } else {
                    ReturnResult returnResult = new ReturnResult();
                    returnResult.returnFail("系统错误");
                    PrintUtil.write(returnResult, response);
                }
            } else {
                String viewName = "500.jsp";
                request.getRequestDispatcher(viewName).forward(request, response);
            }
        }
    }

    private void toView(HttpServletRequest request, HttpServletResponse response, Object result) throws ServletException, IOException {
        if (!EmptyUtils.isEmpty(result)) {
            if (result instanceof String) {
                String viewName = result.toString() + ".jsp";
                request.getRequestDispatcher(viewName).forward(request, response);
            } else {
                PrintUtil.write(result, response);
            }
        }
    }

    protected Object execute(HttpServletRequest request, HttpServletResponse response){
        return "pre/index";
    }
}
